import { defineStore } from 'pinia'

// 定义用户状态存储
export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null,
    isLoggedIn: false
  }),
  
  getters: {
    // 获取登录状态
    getLoginStatus: (state) => state.isLoggedIn,
    // 获取用户信息
    getUserInfo: (state) => state.userInfo
  },
  
  actions: {
    // 设置令牌
    setToken(token) {
      this.token = token
      uni.setStorageSync('token', token)
    },
    
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = !!userInfo
    },
    
    // 登录操作
    async login(username, password) {
      try {
        // 这里是登录API调用的示例，根据实际情况修改
        const response = await uni.request({
          url: 'your-api-url/login',
          method: 'POST',
          data: {
            username,
            password
          }
        })
        
        const { token, userInfo } = response.data
        this.setToken(token)
        this.setUserInfo(userInfo)
        return true
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },
    
    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      uni.removeStorageSync('token')
      uni.reLaunch({ url: '/pages/auth/login' })
    },
    
    // 从本地存储中恢复状态
    restoreFromStorage() {
      const token = uni.getStorageSync('token')
      if (token) {
        this.token = token
        // 这里可以添加获取用户信息的逻辑
      }
    }
  }
}) 